/**
 * Created by KY on 2017/5/4.
 */
const fs = require('fs');
const gulp = require('gulp');
const path = require('path')
const runSequence = require('run-sequence');
// const buffer = require('vinyl-buffer');
// const merge = require('merge-stream');
// gulp.task('replace', function(){
//     gulp.src(['assets/css/layout.css'])
//         .pipe($.replace(/(\d*.\d*){1}rem/g, function(match,p1,offset) {
//             console.log('Found ' + match + ' with param ' + p1 + ' at ' + offset);
//             if(p1.startWith(':')){
//                 return
//             }
//             return p1/2 + 'rem'
//         }))
//         .pipe(gulp.dest('build/'));
// });
const $ = require('gulp-load-plugins')({
    rename: {
        'gulp-clean-css': 'cleanCss',
        'gulp-image-resize': 'imageResize',
        'gulp-svg-sprite': 'svgSprite'
    }
})

const dirs = {
    css: ['assets/css/*.css'],
    src: ['app/**/*.js'],
    assets: [
        'app/tpl/**',
        'assets/fonts/**',
        'assets/img/**',
        'assets/css/**',
        'assets/css/comps/**',
        '!assets/img/sprites-1x',
        '!assets/img/sprites-1x/*',
        '!assets/img/sprites-2x'
    ],
    dest: 'dist'
}

gulp.task('clean', function () {
    return gulp.src([
        dirs.dest + '/*'
    ]).pipe($.clean())
})
gulp.task('copy', function () {
    return gulp.src(dirs.assets, {base: '.'})
        .pipe(gulp.dest(dirs.dest))
})

gulp.task('compress', function () {
    return gulp.src(dirs.src)
        .pipe($.sourcemaps.init())
        .pipe($.babel())
        .pipe($.uglify())
        .pipe($.sourcemaps.write('maps'))
        .pipe(gulp.dest(dirs.dest + '/app'))
})
gulp.task('compress-ldfw', function () {
    return gulp.src(['ldfw/**/*.js', 'ldbiz/**/*.js'], {base: '.'})
        .pipe($.sourcemaps.init())
        .pipe($.babel())
        .pipe($.uglify({
            compress: {
                drop_console: true
            }
        }))
        .pipe(gulp.dest(dirs.dest))
})

gulp.task('sass', function () {
    gulp.src(['./assets/sass/**/*.scss','!./assets/sass/common.scss'],{base: './assets/sass'})
        .pipe($.sass().on('error', $.sass.logError))
        // .pipe($.concat('all.min.css'))
        .pipe($.autoprefixer(
            {
                browsers: ['last 2 versions', 'ie 8'],
                cascade: false
            }
        ))
        .pipe($.cleanCss({
            compatibility: 'ie8',
            level: {
                1: {
                    specialComments: false,
                }
            },
            debug: true
        }, function (details) {
            console.log(details.path+":" + details.stats.originalSize + " -> " + details.stats.minifiedSize )
        }))
        .pipe(gulp.dest(dirs.dest+'/assets/'))

    gulp.src('./assets/sass/**/*.png',{base: './assets/sass'})
        .pipe(gulp.dest(dirs.dest+'/assets/'))
})

gulp.task('sass:watch', function () {
    return gulp.watch('./assets/sass/common.scss', function(){
        gulp.src(['./assets/sass/8000/css/layout.scss'],{base: './assets/sass'})
            .pipe($.sass().on('error', $.sass.logError))
            // .pipe($.concat('all.min.css'))
            .pipe($.autoprefixer(
                {
                    browsers: ['last 2 versions', 'ie 8'],
                    cascade: false
                }
            ))
            .pipe($.cleanCss({
                compatibility: 'ie8',
                level: {
                    1: {
                        specialComments: false,
                    }
                },
                debug: true
            }, function (details) {
                console.log(details.path+":" + details.stats.originalSize + " -> " + details.stats.minifiedSize )
            }))
            .pipe(gulp.dest(dirs.dest+'/assets/'))
    })
})

gulp.task('build', function (cb) {
    runSequence('clean', ['compress','compress-ldfw', 'sass', 'copy'], cb)
})

gulp.task('scp', function () {
    return gulp.src([dirs.dest + '/app/**/*', dirs.dest + '/assets/**/*'], {base: 'dist'})
        .pipe($.scp2({
            host: '172.18.30.192',
            username: 'root',
            password: '123456',
            dest: '/home/fronts/client-ldtamp-invest/'
        }))
        .on('error', function (err) {
            console.log(err)
        })
})


gulp.task('minify-css', function () {
    return gulp.src(dirs.css)
        .pipe($.concat('all.min.css'))
        .pipe($.autoprefixer(
            {
                browsers: ['last 2 versions', 'ie 8'],
                cascade: false
            }
        ))
        .pipe($.cleanCss({
            compatibility: 'ie8',
            level: {
                1: {
                    specialComments: false,
                }
            },
            debug: true
        }, function (details) {
            console.log(details.path+":" + details.stats.originalSize + " -> " + details.stats.minifiedSize )
        }))
        .pipe(gulp.dest(dirs.dest + '/assets/css'))
})


gulp.task('css:watch', function () {
    var watcher = gulp.watch(dirs.css, ['minify-css']);
    watcher.on('change', function (event) {
        console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    })
})

gulp.task('lint-css', function () {
    return gulp
        .src('assets/css/**/*.css')
        .pipe($.stylelint({
            reportOutputDir: 'dist/stylelint',
            reporters: [
                {formatter: 'string', save: 'result.txt'}
            ],
            debug: true
        }))
})

gulp.task('lint-es', function () {
    var dir = dirs.dest + '/eslint',
        path = dir + '/result.txt'
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
    }
    var output = fs.createWriteStream(path, {
        flags: 'w+',
        defaultEncoding: 'utf8'
    })
    var friendlyFormatter = require("eslint-friendly-formatter");
    return gulp.src('app/**/*.js')
        .pipe($.eslint())
        // .pipe($.eslint.format(friendlyFormatter))
        .pipe($.eslint.format())
        .pipe($.eslint.failAfterError())
})

gulp.task('downsize-image', function () {
    return gulp.src('assets/img/sprites-2x/*.png')
        .pipe($.imageResize({width: '50%', height: '50%'}))
        .pipe(gulp.dest('assets/img/sprites-1x'));
})

gulp.task('sprite-image', function () {
    return gulp.src(['assets/img/sprites-1x/*.png'])
        .pipe($.spritesmith({
            imgName: 'img/sprite.png',
            cssName: 'css/sprite.css',
            algorithm: 'binary-tree',
            cssTemplate: "assets/css/sprite/template.css"
        }))
        .pipe(gulp.dest('dist'));
})

gulp.task('sprite-svg', function () {
    let config = {
        shape: {
            dimension: {			// Set maximum dimensions
                maxWidth: 17,
                maxHeight: 17
            }
        },
        mode: {
            // view: {			// Activate the «view» mode
            //     bust: false,
            //     render: {
            //         scss: true		// Activate Sass output (with default options)
            //     },
            //     example:true
            // },
            symbol:{
                render:{
                    scss:true
                },
                example:true
            }
        }
    };
    return gulp.src('assets/img/sprites-1x/*.svg')
        .pipe($.svgSprite(config))
        .pipe(gulp.dest('dist'))
})
